package com.winner.data.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.winner.data.entity.Analysis;
import com.winner.data.entity.AnalysisDetail;
import com.winner.data.entity.request.UserExport;
import com.winner.data.entity.request.UserImport;
import com.winner.data.exception.R;
import com.winner.data.util.excel.EasyExcelUtil;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * easyexcel导入导出,  .xls 和.xlsx 还是有区别的, 建议用新版的.xlsx 作为excel文件的后缀
 *
 * @author wangxinle5
 * @since 2023-01-03
 */
@Slf4j
@RestController
@RequestMapping("/")
public class ExcelController extends BaseController {

    /**
     * localhost:8080/importExcelNoListener  导入excel不带Listener监听器
     */
    @PostMapping("/importExcelNoListener")
    public R importExcelNoListener(@RequestParam(value = "file") MultipartFile file) throws Exception {
        List<UserImport> userList = EasyExcel.read(file.getInputStream()).head(UserImport.class).sheet().doReadSync();
        return R.success();
    }

    /**
     * localhost:8080/importExcel  导入excel带Listener监听器
     */
    @PostMapping("/importExcel")
    public R importExcel(@RequestParam(value = "file") MultipartFile file) throws Exception {
        // 多行头（跳过N行）, 一般默认是1个行头, 不用写sheet().headRowNumber(2)
        EasyExcel.read(file.getInputStream(), UserImport.class, new UserListener("123")).sheet().doRead();
        // 上传文件小于300KB直接成功
        if (file.getSize() / 1024 < 300) {
            return success("导入成功");
        }
        return success("所有数据校验通过, 请10分钟后查看导入的数据");
    }

    /**
     * localhost:8080/exportExcelCommon 导出
     */
    @GetMapping(value = "/exportExcelCommon")
    public void exportExcelCommon(HttpServletResponse response) {
        List<UserExport> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            UserExport userExport = new UserExport();
            userExport.setAge(i);
            userExport.setName("张三");
            userExport.setGender("MALE");
            userExport.setBirthdate("2023-10-01");
            list.add(userExport);
        }
        EasyExcelUtil.writeExcel(list, UserExport.class, "导出文件", response);
    }

    /**
     * localhost:8080/exportExcel 导出
     */
    @GetMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        // 根据入参日期范围生成header,不依赖于数据库是否有数据
        ArrayList<String> dynamicHeaderList = ListUtil.toList("2023-12", "2023-11");
        // 构造查询数据库的
        ArrayList<Analysis> analysisList = new ArrayList<>();
        analysisList.add(new Analysis("一号", "参数1",
            ListUtil.toList(new AnalysisDetail("2023-12", "1", "1.0"), new AnalysisDetail("2023-11", "2", "2.0"))));
        Set<String> orangeSet = new HashSet<>();
        Set<String> redSet = new HashSet<>();
        // 创建接收转换好数据的容器
        List<List<Object>> sheetData = new ArrayList<>();
        // i 从1开始, 方便定位是第一行 j列需要染色
        for (int i = 1; i < analysisList.size() + 1; i++) {
            Analysis analysis = analysisList.get(i - 1);
            List<AnalysisDetail> detailList = analysis.getDetailList();

            List<Object> fixHeaderValue = ListUtil.toList(analysis.getName(), analysis.getParam());
            List<Object> dynamicHeaderValue =
                detailList.stream().map(AnalysisDetail::getValue).collect(Collectors.toList());
            int size = fixHeaderValue.size();
            fixHeaderValue.addAll(dynamicHeaderValue);
            sheetData.add(fixHeaderValue);

            // 构造第i行第j列需染色的map 第几行 第几列(列的数字是从0开始计算的, -1表示所有列或所有行)
            for (int j = size; j < detailList.size() + size; j++) {
                AnalysisDetail analysisDetail = detailList.get(j - size);
                if (StrUtil.equals(analysisDetail.getStatus(), "1")) {
                    orangeSet.add(i + String.valueOf(j));
                }
                if (StrUtil.equals(analysisDetail.getStatus(), "2")) {
                    redSet.add(i + String.valueOf(j));
                }
            }
        }
        ArrayList<String> fixHeaderList = ListUtil.toList("名称", "参数");
        EasyExcelUtil.writeExcelBySheetData(sheetData, fixHeaderList, dynamicHeaderList, orangeSet, redSet, "导出文件",
            response);
    }

    /**
     * localhost:8080/exportMapListToDisk 导出
     */
    @GetMapping(value = "/exportMapListToDisk")
    public void exportMapListToDisk() {
        List<TreeMap<String, Object>> exportList = new ArrayList<>();
        TreeMap<String, Object> objectObjectTreeMap = new TreeMap<>();
        objectObjectTreeMap.put("name", "张三");
        objectObjectTreeMap.put("age", 18);
        exportList.add(objectObjectTreeMap);
        List<List<Object>> sheetData = new ArrayList<>();
        exportList.forEach(a -> {
            List<Object> fixHeaderValue = Arrays.asList(a.values().toArray());
            sheetData.add(fixHeaderValue);
        });
        List<String> fixHeaderList = exportList.stream().findFirst().map(a -> new ArrayList<>(a.keySet())).orElse(null);
        EasyExcelUtil.writeExcelBySheetData(sheetData, fixHeaderList, "D:\\导出文件.xlsx");
    }

}
